package com.coolw.spring.statemachine.util;

import com.coolw.spring.statemachine.constant.StateMachineConst;
import com.coolw.spring.statemachine.support.BaseEvent;
import com.coolw.spring.statemachine.support.BaseState;
import org.dromara.hutool.core.util.BooleanUtil;
import org.springframework.statemachine.StateMachine;

import java.util.Map;

/**
 * 状态机工具类
 *
 * @author coolw
 * @date 2024/4/16 14:15
 */
public final class StateMachineUtil {

    /**
     * 检查状态执行是否发生异常,如果有异常则抛出异常
     *
     * @param stateMachine 状态机
     * @throws Exception 异常信息
     */
    public static <S extends BaseState, E extends BaseEvent> void checkActionError(StateMachine<S, E> stateMachine)
            throws Exception {
        Map<Object, Object> varMap = stateMachine.getExtendedState().getVariables();
        Boolean hasError = (Boolean) varMap.get(StateMachineConst.HAS_ERROR);
        if (BooleanUtil.isTrue(hasError)) {
            throw (Exception) varMap.get(StateMachineConst.ERROR);
        }
    }
}
